<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ include file="/include/taglibs.jsp" %>
<html>
<head>
    <%@include file="/include/header.html" %>
    <link rel="stylesheet" href="${ctx}/statics/css/blanceDrop.css">
    <link rel="stylesheet" href="${ctx}/statics/css/update.css">
    <link rel="stylesheet" href="${ctx}/statics/css/common.css">
    <link rel="stylesheet" href="${ctx}/libjs/plugins/laydate/laydate.css">
    <script src="${ctx}/libjs/plugins/laydate/laydate.js"></script>
    <link rel="stylesheet" href="${ctx}/libjs/plugins/bootstrap-table-pagejump/bootstrap-table-pagejump.css">
    <script src="${ctx}/libjs/plugins/bootstrap-table-pagejump/bootstrap-table-pagejump.js"></script>
    <link rel="stylesheet" href="${ctx}/libjs/plugins/bootStrap-table-fixed-column/bootstrap-table-fixed-columns.css">
    <script src="${ctx}/libjs/plugins/bootStrap-table-fixed-column/bootstrap-table-fixed-columns.js"></script>
    <style>
        .bootstrap-table .fixed-table-container .table thead th .th-inner {
            text-align: center !important;
        }
        .btn{
            margin-top: 0 !important;
        }
        .table > tbody > tr > .operate-td, .table > tfoot > tr > .operate-td{
            padding: 0 !important;
        }
        #pdfDom .auditingBtn {
            margin-bottom: 80px !important;
        }
        #pdfDom table{
            border-collapse: collapse;
            border-bottom: 1px solid grey;
        }
        #pdfDom td{
            width: 800px;
            padding-left: 10px;
            line-height: 30px;
            height: 100%;
            color: #000;
        }
        #pdfDom tbody{
            display: flex;
            flex-wrap: wrap;
        }
        #pdfDom tbody tr{
            width: 50%;
            border: 1px solid grey;
            border-bottom: 1px solid grey;
        }
        #pdfDom .totalTr td{
            background: #99ccff;
        }
        .fixed-table-body-columns1{
            /*left: unset !important;*/
            width: 220px !important;
            margin-left:0 !important;
            top: 55px !important;
            border-right: none;
            border-top:2px solid #e7e7e7
        }
    </style>
</head>

<script type="text/javascript">
    $('#topLink', window.parent.document).html(function (i, origText) {
        return '<ol class="breadcrumb">' +
            '<li class="breadcrumb-item">' +
            '<a href="">主页</a>' +
            '</li>' +
            '<li class="breadcrumb-item">' +
            '<a>分销商结算</a>' +
            '</li>' +
            '<li class="breadcrumb-item">' +
            '<strong>对账单</strong>' +
            '</li>' +
            '<li class="breadcrumb-item">' +
            '<a href="javascript:window.history.go(-1);"><i class="fa fa-times"></i> 返回</a>' +
            '</li>' +
            '</ol>';
    });

    var has_add = '';
    var has_edit = '';
    var has_delete = '';
</script>

<body class="gray-bg">
<div class="wrapper wrapper-content " style="overflow: auto!important;">
    <div class="pdfContent"></div>
    <input type="hidden" name="billOrderId" id="billOrderId" >
    <input type="hidden" id="billTotalMoney" >
    <div class="col-sm-12" style="position: absolute;top: 0">
        <div class="ibox">
            <div class="ibox-body">
                <div class="row">
                    <select class="form-control shortInput input-distance" name="tenantOperatorCode" id="tenantOperatorCode">
                        <option value="">分销商名称</option>
                        <c:forEach items="${tenantOperatorList}" var="tenantOperator">
                            <option value="${tenantOperator.tenantOperatorCode}">${tenantOperator.operatorName}</option>
                        </c:forEach>
                    </select>
                    <select name="elecStationId" id="elecStationId" class="form-control shortInput input-distance">
                        <option value="">站点选择</option>
                    </select>
                    <input id="billOrderNum" name="billOrderNum" type="text"
                           class="form-control shortInput input-distance"
                           placeholder="结算订单号">
                    <%-- 状态 0待审核 1运营商已审核 2复核中 3结算完成 默认0 --%>
                    <select name="status" id="status" class="form-control shortInput input-distance">
                        <option value="">状态</option>
                        <option value="0">待审核</option>
                        <option value="1">待确认账单</option>
                        <option value="2">待复核</option>
                        <option value="3">结算完成</option>
                        <option value="4">待推送</option>
                    </select>
                    <input id="startTime" name="startTime" type="text" class="form-control shortInput input-distance"
                           placeholder="账单开始时间" readonly>
                    <input id="endTime" name="endTime" type="text" class="form-control shortInput input-distance"
                           placeholder="账单结束时间" readonly>
                    <button class="btn btn-success input-distance" id="searchBtn" onclick="acctBillOrder.reLoad()">查询</button>
                    <button type="button" class="btn btn-success marginright-auto input-distance"
                            onclick="acctBillOrder.exportAcctBillOrder()">
                        导出
                    </button>
                    <button type="button" class="btn btn-success marginright-auto input-distance batchFailure">
                        批量下载对账单
                    </button>
                </div>
                <table id="exampleTable" data-mobile-responsive="true" >
                </table>

                <%--  关联审核明细的模态框  --%>
                <%--  关联审核明细的模态框  --%>
                <div class="auditingModal hide">
                    <span style="position: absolute;right: 20px;top: 5px;cursor: pointer" onclick="acctBillOrder.closeBtn()">X</span>
                    <div class="title">请认真查看结算单数据，如需调整金额，可在下面调整金额操作框进行调整！</div>
                    <div class="inputBlock">
                        <span class="label">调整电费:</span><input type="number"  id="adjustElecAmount" name="adjustElecAmount" step="0.01"><span class="inputTips">向上调是正数，向下调是负数</span>
                    </div>
                    <div class="inputBlock">
                        <span class="label">调整服务费:</span><input type="number"  id="adjustServiceAmount" name="adjustServiceAmount" step="0.01"><span class="inputTips">向上调是正数，向下调是负数</span>
                    </div>
                    <div class="inputBlock">
                        <span class="label" style="flex-shrink: 0">备注:</span><textarea style="width: 100%" rows="5" id="remark"
                                                                                       name="remark"></textarea>
                    </div>
                    <div class="buttonBlock">
                        <div class="cancleButton" onclick="acctBillOrder.closeBtn()">取消</div>
                        <div class="confirmButton addReviewAcctBillOrder">确定</div>
                    </div>
                </div>

            </div>

        </div>
    </div>
</div>
<script type="text/javascript" src="${ctx}/appjs/acct/acctBillOrderTotal.js"></script>
<script src="${ctx}/libjs/plugins/jspdf/html2canvas.js"></script>
<script src="${ctx}/libjs/plugins/jspdf/jspdf.js"></script>
<script>
    var length  = 0;
    $(".wrapper-content").on("click",".batchFailure",function () {
        var rows = $("#exampleTable").bootstrapTable('getSelections');// 获得要下载的数据
        console.log(rows)
        if (rows.length == 0) {// rows 主要是为了判断是否选中，下面的else内容才是主要
            alert("请先选择要下载的对账单!");
            return;
        }
        // else if(rows.length >5){
        //     alert("每次下载账单不能大于5个");
        //     return;
        // }
        else {
            // $('#exampleTable').css("height",$(window).height() - 1080)
            $(".pdfContent").html("")
            var billOrderIds = new Array();// 声明一个数组
            $(rows).each(function () {// 通过获得别选中的来进行遍历
                billOrderIds.push(this.billOrderId); // cid为获得到的整条数据中的一列
            });
            for(var i = 0; i<billOrderIds.length;i++){
                detailAcctBillOrders(billOrderIds[i])
            }
            setTimeout(function () {
                if(confirm("您确认下载PDF文件吗?")){
                    length = $(".billSection").length;
                    makeMpdf($(".billSection").eq(0).find("#stationName").val()+"结算对账单"+ $(".billSection").eq(0).find("#billEndTime").val(),$(".billSection").eq(0),0)
                    // makeMpdf($(".billSection").eq(i).find("#stationName").val()+"结算对账单"+ $(".billSection").eq(i).find("#billEndTime").val(),$(".billSection").eq(i))

                    setTimeout(function () {
                        $("#searchBtn").click()
                    },1000)
                }

            },500)

            // memberIdList = JSON.stringify(memberIds);
            // batchForcedFailure(memberIdList)
        }
    })

    function detailAcctBillOrders(billOrderId) {
        $.ajax({
            "type":"get",
            "url":"${ctx}/acctTenantOperator/detailAcctBillOrders/"+billOrderId,
            "success":function (data) {
                if(data.status==200){
                    var acctBillOrderResultVo = data.data.acctBillOrderResultVo;
                    var acctContractList = data.data.acctContractList;
                    var status = ''
                    if(acctBillOrderResultVo.status == 0){
                        status = '待审核'
                    }else if(acctBillOrderResultVo.status == 1){
                        status = '待确认账单'
                    }else if(acctBillOrderResultVo.status == 2){
                        status = '复核中'
                    }
                    else if(acctBillOrderResultVo.status == 3){
                        status = '结算完成'
                    }
                    else if(acctBillOrderResultVo.status == 4){
                        status = '待推送'
                    }
                    var elecTrStr = '';
                    var acctContractListStr = '';
                    if(data.data.acctSubItems){
                        for(var j=0;j<data.data.acctSubItems.length;j++){
                            elecTrStr +=` <tr class="elecTr">
                    <td></td>
                </tr>
                <tr class="serviceTr">
                    <td>\${data.data.acctSubItems[j].subItem}</td>
                </tr>`
                        }
                    }else{
                        elecTrStr = ''
                    }

                    if(acctContractList.length>0){
                        for(var k=0;k<acctContractList.length;k++){
                            acctContractListStr +=`<div class="block">合同名称：\${acctContractList[k].contractName}<span class="checkIcon" style="cursor: pointer"
                                                                      onclick="contractModal('\${acctContractList[k].contractPdf}')">查看</span>
                                                </div>`
                        }
                    }else{
                        acctContractListStr = ''
                    }

                    var str = `<div class="billSection" id="pdfDom">
                  <input type="hidden" name="stationName" id="stationName" value="\${acctBillOrderResultVo.stationName}">
                  <input type="hidden" name="billEndTime" id="billEndTime" value="\${acctBillOrderResultVo.billEndTime}">
    <input type="hidden" name="billOrderId" id="billOrderId" value="\${acctBillOrderResultVo.billOrderId}">
    <input type="hidden" id="billTotalMoney" value="\${acctBillOrderResultVo.billTotalMoney}">
    <h1 class="billTitle">\${acctBillOrderResultVo.stationName}结算对账单</h1>
    <div class="topBlock">
        <span>结算订单号：\${acctBillOrderResultVo.billOrderNum}</span>
        <span>结算订单期间：\${acctBillOrderResultVo.billStartTime}~\${acctBillOrderResultVo.billEndTime}"</span>
    </div>
    <input type="hidden" id="contractPath" value="\${data.data.contractPath}">
    <div class="contentBlock">
        <div class="blockTitle">
            对应分销商&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span >\${data.data.tenantOperator.operatorName}</span>
            <div class="block" style="margin-top: 0;margin-left: auto">
                <span class="label">结算状态:</span>
                <span class="num">\${status}</span>
            </div>
        </div>
        <div class="blockTitle">订单信息</div>
        <div class="block">
            <span class="label">订单数:</span>
            <span class="num">\${acctBillOrderResultVo.orderCount?acctBillOrderResultVo.orderCount:0}</span>
        </div>
        <div class="block">
            <span class="label">平台电量:</span>
            <span class="num">\${acctBillOrderResultVo.totalPower?acctBillOrderResultVo.totalPower:'0.000'}</span>
        </div>
        <div class="block">
            <span class="label">平台电费:</span>
            <span class="num">\${acctBillOrderResultVo.totalElecMoney?acctBillOrderResultVo.totalElecMoney:'0.00'}</span>
        </div>
        <div class="block">
            <span class="label">平台服务费:</span>
            <span class="num">\${acctBillOrderResultVo.totalSeviceMoney?acctBillOrderResultVo.totalSeviceMoney:'0.00'}</span>
        </div>
        <div class="block">
            <span class="label">平台优惠金额:</span>
            <span class="num">\${acctBillOrderResultVo.totalDiscountMoney?acctBillOrderResultVo.totalDiscountMoney:'0.00'}</span>
        </div>
        <div class="block">
            <span class="label">平台总金额:</span>
            <span class="num">\${acctBillOrderResultVo.totalMoney?acctBillOrderResultVo.totalMoney:'0.00'}</span>
        </div>
        <div class="block">
            <span class="label">平台实收金额:</span>
            <span class="num">\${acctBillOrderResultVo.payAmount?acctBillOrderResultVo.payAmount:'0.00'}</span>
        </div>
        <div class="block \${(acctBillOrderResultVo.consultOrderAmount != '' && acctBillOrderResultVo.consultOrderAmount != null)?'':'hide'}">
            <span class="label">咨询订单金额:</span>
            <span class="num">\${acctBillOrderResultVo.consultOrderAmount?acctBillOrderResultVo.consultOrderAmount:'0.00'}</span>
        </div>
    </div>
    <div class="contentBlock">
        <div class="blockTitle">结算信息</div>
        <%--<div class="block ruleBlock">结算电费=${acctBillOrderResultVo.elecAcctRule}</div>--%>
        <%--<div class="block ruleBlock">结算服务费=${acctBillOrderResultVo.serviceAcctRule}</div>--%>
        <table style="width: 100%;margin-top: 20px">
            <tr style="width: 100%">
                <td style="width: 100%;float: right;text-align:right;background:#99ccff;padding-right: 20px">结算总金额（元）:\${acctBillOrderResultVo.totalAcctAmount?acctBillOrderResultVo.totalAcctAmount:'0.00'}</td>
            </tr>
            <tr class="elecTr">
                <td>平台电费=\${acctBillOrderResultVo.totalElecMoney?acctBillOrderResultVo.totalElecMoney:'0.00'}</td>
            </tr>
            <tr class="serviceTr">
                <td>平台服务费=\${acctBillOrderResultVo.totalSeviceMoney?acctBillOrderResultVo.totalSeviceMoney:'0.00'}</td>
            </tr>
            \${elecTrStr}
            <tr class="elecTr">
                <td>+调整电费=\${acctBillOrderResultVo.adjustElecAmount?acctBillOrderResultVo.adjustElecAmount:'0.00'}</td>
            </tr>
            <tr class="serviceTr">
                <td>+调整服务费=\${acctBillOrderResultVo.adjustServiceAmount?acctBillOrderResultVo.adjustServiceAmount:'0.00'}</td>
            </tr>
            <tr class="totalTr">
                <td>结算电费（元）:\${acctBillOrderResultVo.elecAcctAmount?acctBillOrderResultVo.elecAcctAmount:'0.00'}</td>
            </tr>
            <tr class="totalTr">
                <td>结算服务费（元）:\${acctBillOrderResultVo.serviceAcctAmount?acctBillOrderResultVo.serviceAcctAmount:'0.00'}</td>
            </tr>
        </table>
    </div>
    <div class="contentBlock remarkBlock">
        <div class="blockTitle">备注</div>
            <div class="remark \${acctBillOrderResultVo.remark?'':'hide'}">\${acctBillOrderResultVo.remark}</div>
    </div>
    <div class="contentBlock contractBlock">
        <div class="blockTitle">合同信息</div>
        <%--<div class="block">合同编号：JT-DSF-2019-07--广州启天新能源科技有限公司<span class="checkIcon">查看</span></div>--%>
        <%--<div class="block">合同编号：JT-DSF-2019-07--广州启天新能源科技有限公司<span class="checkIcon">查看</span></div>--%>
       \${acctContractListStr}
    </div>
    <div class="tips">*以上信息请务必慎重确认，确认无误后再发送给分销商，以便减少结算错误率。</div>
    <div class="sealBlock \${(acctBillOrderResultVo.status != 0 && acctBillOrderResultVo.status != 2)?'':'hide' }">
        <img src="${ctx}/statics/img/seal.png" class="seal" alt="">
        <p>日期：\${acctBillOrderResultVo.pushTime?acctBillOrderResultVo.pushTime:''}</p>
    </div>
    <div class="confirmModal hide">
        <span style="position: absolute;right: 10px;top: 5px;cursor: pointer" onclick="closeBtn()">X</span>
        <div>请认真查看结算单数据，如有异议，请操作”有异议，打回“操作，让平台再次进行审核，
            打回后，务必提前联系平台，加快处理效率，谢谢！
        </div>
        <div class="inputBlock">
            <span class="label" style="flex-shrink: 0">驳回原因:</span><textarea style="width: 100%" rows="5" id="rejectRemark"
                                                                             name="rejectRemark"></textarea>
        </div>
        <div class="buttonBlock">
            <div class="cancleButton">有异议，打回</div>
            <div class="confirmButton">确认没问题</div>
        </div>
    </div>
    <div class="invoiceModal" id="invoiceModal" style="display: none">
        <div class="contentBlock">
            <iframe id="myFrameId" name="myFrameName" src="" scrolling="no" frameborder="0"></iframe>
            <%--<ul>--%>

            <%--</ul>--%>
        </div>
    </div>

    <%--  关联审核明细的模态框  --%>
    <div class="auditingModal hide">
        <span style="position: absolute;right: 20px;top: 5px;cursor: pointer" onclick="acctBillOrder.closeBtn()">X</span>
        <div class="title">请认真查看结算单数据，如需调整金额，可在下面调整金额操作框进行调整！</div>
        <div class="inputBlock">
            <span class="label">调整电费:</span><input type="number"  id="adjustElecAmount" name="adjustElecAmount"><span class="inputTips">向上调是正数，向下调是负数</span>
        </div>
        <div class="inputBlock">
            <span class="label">调整服务费:</span><input type="number"  id="adjustServiceAmount" name="adjustServiceAmount"><span class="inputTips">向上调是正数，向下调是负数</span>
        </div>
        <div class="inputBlock">
            <span class="label" style="flex-shrink: 0">备注:</span><textarea style="width: 100%" rows="5" id="remark"
                                                                           name="remark"></textarea>
        </div>
        <div class="buttonBlock">
            <div class="cancleButton addReviewAcctBillOrder billPage">不需调整</div>
            <div class="confirmButton addReviewAcctBillOrder billPage">确定</div>
        </div>
    </div>
</div>`

                    $(".pdfContent").append(str);
                }
            }
        })
    }

    function makeMpdf(pdfName, target,index) {
        //var target = document.getElementsByClassName("right-aside")[0];
        target.css("background","#fff")
        if (pdfName == '' || pdfName == undefined) pdfName = "content";
        var scale = 2//放大倍数
        var canvas = document.createElement("canvas");
        console.log(target)
        html2canvas(target[0], {

            onrendered: function (canvas) {
                var contentWidth = canvas.width;
                var contentHeight = canvas.height;
                //一页pdf显示html页面生成的canvas高度;
                var pageHeight = contentWidth /841.89* 592.28;
                //未生成pdf的html页面高度
                var leftHeight = contentHeight;
                //页面偏移
                var position = 0;
                //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
                var imgWidth = 841.89;
                var imgHeight = 841.89 / contentWidth * contentHeight;
                var pageData = canvas.toDataURL('image/jpeg', 1.0);

                var pdf = new jsPDF('l', 'pt', 'a4');

                //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
                //当内容未超过pdf一页显示的范围，无需分页
                if (leftHeight < pageHeight) {
                    pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
                } else {
                    while (leftHeight > 0) {
                        pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                        leftHeight -= pageHeight;
                        position -= 595.28;
                        //避免添加空白页
                        if (leftHeight > 0) {
                            pdf.addPage();
                        }
                    }
                }
                pdf.save(pdfName + ".pdf");
                // if(index+1<=length){
                    console.log(index+1)
                    makeMpdf($(".billSection").eq(index+1).find("#stationName").val()+"结算对账单"+ $(".billSection").eq(index+1).find("#billEndTime").val(),$(".billSection").eq(index+1),index+1)
                // }
            }
        })
        // $(".billSection").eq(index).remove()
    }

</script>
<script type="text/javascript">

    //下拉组件注册
    $(function () {
        $('#tenantOperatorCode').searchableSelect();
    })
    // //日期范围限制
    var start = {
        elem: '#startTime',
        format: 'YYYY-MM-DD hh:mm:ss',
        // theme: '#3195f0',
        // min: laydate.now(), //设定最小日期为当前日期
        // max: '2099-06-16 23:59:59', //最大日期
        istime: true,
        istoday: false
    };
    var end = {
        elem: '#endTime',
        format: 'YYYY-MM-DD hh:mm:ss',
        // theme: '#3195f0',
        // min: laydate.now(),
        // max: '2099-06-16 23:59:59',
        istime: true,
        istoday: false
    };
    laydate(start);
    laydate(end);
    laydate.skin('molv');//皮肤


    function ListElecStation() {
        var tenantOperatorCode = $("#tenantOperatorCode").val()
        $.ajax({
            "url": prefix + "/ListElecStation",
            "type": "GET",
            "data": {
                'tenantOperatorCode': tenantOperatorCode,
            },
            "success": function (data) {
                $("#elecStationId").html("")

                var str = '<option value="" >站点选择</option>'
                if (data.data) {
                    for (var i = 0; i < data.data.length; i++) {
                        str += "<option value=" + data.data[i].elecStationId + " >" + data.data[i].stationName + "</option>";

                    }
                }

                $("#elecStationId").append(str);
                $("#elecStationId + div").remove()
                $('#elecStationId').searchableSelect();
                //console.log(str)

            },
            "complete": function () {
            }
        })
    }

    ListElecStation();

    $("#tenantOperatorCode").change(function () {
        var tenantOperatorCode = $("#tenantOperatorCode").val()
        ListElecStation(tenantOperatorCode);
    })

    acctBillOrder.init();
</script>
</body>
</html>